/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.dishes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.Industries;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.service.dishes.*;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.serviceapp.service.thirdpart.BranchPlatformApiServiceImpl;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.SearchFilterHelper;
import com.qinyetech.springstage.core.entity.search.SearchOperator;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

/**
 * ClassName: DishesMenusController <br/>
 * Function: dishesMenu [菜谱] <br/>
 * date: 2018-11-26 10:29:38 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/dishes/dishesMenus")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_dishesMenu:read",name ="菜谱",deleteAble = false)
public class DishesMenusController extends BaseManagementController{

	@Autowired
	private DishesMenuService dishesMenuService;
	@Autowired
	private DistrictService districtService;
	@Autowired
    private DishesStoreService dishesStoreService;
	@Autowired
    private DishesMenuDetailService dishesMenuDetailService;
	@Autowired
    private DishesMenuBranchService dishesMenuBranchService;
	@Autowired
    private BranchService branchService;
	@Autowired
    private SyncDishesRecordService syncDishesRecordService;
	@Autowired
    private BranchPlatformApiServiceImpl branchPlatformApiService;
	@Autowired
    private DishesService dishesService;
    //TODO include的字段,支持jsonPath
	private final String [] keys = {"id","name","effectiveTime","storeId","operatorName","operateTime","state","branchs",
            "dishesDetails","materialDetails","costCard","branchIndustry","account"};

//    @RequiresPermissions("management_dishesMenu:show")
    @PermissionInfo(code = "management_dishesMenu:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<DishesMenu> dishesMenuPage = dishesMenuService.findAll(searchable);
        if(CollectionUtils.isNotEmpty(dishesMenuPage.getContent())){
            searchable = SearchableUtils.newSearchableWithMerchantFilter();
            Branch branch = null;
            String branchs = "";
            int count = 0;
            List<DishesMenuBranch> branchList = null;
            for (DishesMenu menu : dishesMenuPage.getContent()) {
                branchs = "";
                count =0;
                searchable.addSearchParam("menuId_eq",menu.getId());
                branchList = dishesMenuBranchService.findWithSort(searchable);
                if(CollectionUtils.isNotEmpty(branchList)){
                    branch = branchService.findById(branchList.get(0).getBranchId());
                    menu.setBranchIndustry(branch.getIndustry());
                    menu.setName(branch.getName());
                    menu.setState(branch.getState());
                    menu.setAccount(branch.getUsername());
                    /*for (DishesMenuBranch menuBranch : branchList) {
                        branch = branchService.findById(menuBranch.getBranchId());
                        if (count<=3){
                            branchs+=branch.getName()+",";
                        }else {
                            break;
                        }
                        count++;
                    }*/
                }
                menu.setBranchs(StringUtils.isBlank(branchs)?"":branchs.substring(0,branchs.length()-1));

            }
        }
        return ok("查询成功", JSONUtils.include(dishesMenuPage, keys));
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("dishesMenu",JSONUtils.include(new DishesMenu(), keys));
        initFormDate(map,null);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_dishesMenu:create")
    @PermissionInfo(code = "management_dishesMenu:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject dishesMenu, BindingResult bindingResult){
//        if(dishesMenuService.exists(buildExists(null, "no", dishesMenu.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }

        dishesMenuService.saveData(dishesMenu,CurrentAccountUtils.getAuthenticatedMerchantGroupID(),
                CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute DishesMenu dishesMenu){
        return ok("查询成功", JSONUtils.include(dishesMenu, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute DishesMenu dishesMenu){
        QyMap map=QyMap.NEW();
        map.setv("dishesMenu",JSONUtils.include(dishesMenu, keys));
        //菜谱明细
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("menuId_eq",dishesMenu.getId());
        List<DishesMenuDetail> details = dishesMenuDetailService.findWithSort(searchable);
        map.setv("dishess",JSONUtils.include(details,"dishesId"));
        //门店详情
        List<DishesMenuBranch> branchs = dishesMenuBranchService.findWithSort(searchable);
        Branch branchEn = null;
        if(CollectionUtils.isNotEmpty(branchs)){
            for (DishesMenuBranch branch : branchs) {
                branchEn = branchService.findById(branch.getBranchId());
                branch.setLabel(branchEn.getName());
            }
        }
        map.setv("branchs",JSONUtils.include(branchs,"branchId","districtId","label"));
        initFormDate(map,dishesMenu);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_dishesMenu:update")
    @PermissionInfo(code = "management_dishesMenu:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@RequestBody JSONObject dishesMenu,BindingResult bindingResult){
//        if(dishesMenuService.exists(buildExists(null, "no", dishesMenu.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        dishesMenuService.saveData(dishesMenu,CurrentAccountUtils.getAuthenticatedMerchantGroupID(),CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_dishesMenu:destory")
    @PermissionInfo(code = "management_dishesMenu:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        //删除菜谱相关信息
        dishesMenuService.deletedMenuDetails(id);
        dishesMenuService.logicDelete(id);
        return ok("删除成功", null);
    }


    /**
     * 修改状态
     *
     * @param id
     * @return
     */
    @RequiresPermissions("management_dishesMenu:updateState")
    @PermissionInfo(code = "management_dishesMenu:updateState",name ="修改状态",deleteAble = false)
    @GetMapping("/updateState")
    public ResponseResult<String> updateState(Long id){
        DishesMenu menu = dishesMenuService.findById(id);
        if(menu.getState()== State.NORMAL){
            menu.setState(State.DISABLED);
        }else {
            menu.setState(State.NORMAL);
        }
        dishesMenuService.update(menu);
        return ok("操作成功", null);
    }

    /**
     * 查看所有门店
     *
     * @param id
     * @return
     */
    @GetMapping("/showAllBranchs")
    public ResponseResult<String> showAllBranchs(Long id){
        DishesMenu menu = dishesMenuService.findById(id);
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("menuId_eq",menu.getId());
        List<DishesMenuBranch> branchList = dishesMenuBranchService.findWithSort(searchable);
        Branch branch = null;
        if(CollectionUtils.isNotEmpty(branchList)){
            for (DishesMenuBranch menuBranch : branchList) {
                branch = branchService.findById(menuBranch.getBranchId());
                menuBranch.setLabel(branch.getName());
            }
        }
        return ok("操作成功", JSONUtils.include(branchList,"id","branchId","districtId","label"));
    }


    /**
     * 根据菜谱获取菜 和 门店
     *
     * @param menuId
     * @return
     */
    @GetMapping("/getDishesByMenu")
    public ResponseResult<String> getDishesByMenu(Long menuId){
        //获取菜品信息
        List<Map<String,Object>> detailList = dishesMenuDetailService.getMenuDetails(menuId);
        QyMap map = QyMap.map("dishesList",detailList);
        //获取分店信息
        //机构
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("menuId_eq",menuId);
        List<DishesMenuBranch> branchList = dishesMenuBranchService.findWithSort(searchable);
        List<Long> branchIds = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(branchList)){
            for (DishesMenuBranch branch : branchList) {
                branchIds.add(branch.getBranchId());
            }
        }
        if (!CurrentAccountUtils.getAuthenticatedIsAdmin()){
            String permissions = CurrentAccountUtils.getAuthenticatedManageBranch();
            if (StringUtils.isNotBlank(permissions)){
                List<Long> bids = JSON.parseArray(permissions,Long.class);
                //获取两个集合的交集
                branchIds = branchIds.stream().filter(item -> bids.contains(item)).collect(toList());
            }else {
                branchIds = Lists.newArrayList();
            }
        }
        List<District> list=districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),true,branchIds,true);
        map.setv("districts",list);
        return ok("操作成功", map);
    }

    /**
     * 获取发布记录
     * @param id 发布id
     * @return
     */
    @GetMapping("/getRecords")
    public ResponseResult<String> getRecords(Searchable searchable,Long id){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        searchable.addSearchParam("menuId_eq",id);
        searchable.addSort(Sort.Direction.DESC,"issueTime");
        Page<SyncDishesRecord> records = syncDishesRecordService.findAll(searchable);
        QyMap map = QyMap.map("records",JSONUtils.include(records,"id","storeId","storeName","branchId","branchName",
                "issueTime","content","operatorName"));
        DishesMenu dishesMenu = dishesMenuService.findById(id);
        DishesStore store = dishesStoreService.findById(dishesMenu.getStoreId());
        map.setv("storeType",store.getIndustry().getKey());
        return ok("操作成功", map);
    }

    /**
     * 获取发布记录
     * @param dishesId
     * @return
     */
    @GetMapping("/deleteDishes")
    public ResponseResult<String> deleteDishes(Long branchId,Long dishesId){
        log.info("-=========---:",branchId);
        log.info("-=========---:",dishesId);
        Long merchantId = branchService.getMerchantIdByBranchId(branchId);
        Dishes dishes = dishesService.findById(dishesId);
        boolean boo = branchPlatformApiService.deleteBranchDishesDataByOne(merchantId,dishes.getUuid());
        return ok("操作成功", boo);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            DishesMenu dishesMenu = dishesMenuService.findById(Long.valueOf(id));
            model.addAttribute(dishesMenu);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap,DishesMenu dishesMenu){
        //机构
//        List<District> list=districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),true);
//        qyMap.setv("districts",getDistricts());
        if(dishesMenu!=null){
            Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
            searchable.addSearchParam("menuId_eq",dishesMenu.getId());
            List<DishesMenuBranch> branchList = dishesMenuBranchService.findWithSort(searchable);
            Branch branch = null;
            searchable = SearchableUtils.newSearchableWithMerchantFilter();
            if(CollectionUtils.isNotEmpty(branchList)){
                branch = branchService.findById(branchList.get(0).getBranchId());
                if(Industries.getKeyByText(branch.getIndustry())=="ZC" || Industries.getKeyByText(branch.getIndustry())=="KC"){
                   searchable.addSearchFilter(SearchFilterHelper.or(
                           SearchFilterHelper.newCondition("industry", SearchOperator.eq,"ZC"),
                           SearchFilterHelper.newCondition("industry",SearchOperator.eq,"KC")
                   ));
                }else {
                    searchable.addSearchParam("industry_eq",Industries.getKeyByText(branch.getIndustry()));
                }
            }else {
                searchable.addSearchParam("id_eq",000);
            }
            //菜品库
            List<DishesStore> storeList = dishesStoreService.findWithSort(searchable);
            qyMap.setv("storeList",JSONUtils.include(storeList,"id","name","state","industry"));
        }


    }

}